<?php
namespace Member\Controller;
use Think\Controller;
class CompanyController extends BaseController {
	//绑定角色
	public function bind_role(){
		$m=M('DepartmentCompany');
		$list=$m->select();
		$this->assign('list',$list);
		$this->display();
	}
	public function confirm_bind_role(){
		$m=M('User');
		$ids=I('ids');
		$ids=explode(',',$ids);
		$role_id=I('role_id');
		foreach($ids as $k=>$v){
			$data['department_id']=$role_id;
			$res=$m->where(array('id'=>$v))->save($data);
			if($res===false){
				$this->error('更新出错');
			}else{
				//同步角色
				continue;
			}
		}
		$this->success('更新成功');
	}

    public function index(){
        if(I("get.name")!==null && I("get.name")!==''){
            $where['company']=I("get.name");
        }
		$where['member']=session('member');
        $user = M('user');
		$department = M('DepartmentCompany');
        $count      = $user->where($where)->count();
        $Page       = new \Think\Page($count,15);
        $show       = $Page->show();
        $list = $user->where($where)->limit($Page->firstRow.','.$Page->listRows)->order("id desc")->select();
		foreach($list as $k=>$v){
			$department_name=$department->where(array('id'=>$v['department_id']))->find();
			$list[$k]['department_name']=$department_name['name'];
		}
		// dump($list);
        $this->assign('list',$list);
        $this->assign('page',$show);
        $this->assign('count',$count);
        $this->display();
    }
    public function warehouse($id){
        if($id==''){
            alert(0,'操作有误');
        }
        $warehouse_group_id=M('user_warehouse')->where("user_id='".$id."'")->getField('warehouse_group_id');
        $group_id=explode(',',$warehouse_group_id);
		$where['member']=session('member');
        $warehouse=M('warehouse')->where($where)->select();
        foreach($warehouse as $k=>$v){
            if(in_array($v['id'],$group_id)){
                $warehouse[$k]['checked']=1;
            }
        }
        $this->assign('list',$warehouse);
        $this->assign('user_id',$id);
        $this->display();
    }
    public function warehouseEditD($id,$user_id){
        if($id==''){
            alert(0,'操作有误');
        }
        $group_id=explode('@',$id);
        $id='';
        foreach($group_id as $v){
            if($v!==''){
                $id.=','.$v;
            }
        }
        $data['warehouse_group_id']=ltrim($id,',');
        $data['operator']=session('admin');
        if(M("user_warehouse")->where("user_id='".$user_id."'")->count()>0){
            $result= M("user_warehouse")->where("user_id='".$user_id."'")->save($data);
        }else{
            $data['user_id']=$user_id;
            $result= M("user_warehouse")->where("user_id='".$user_id."'")->add($data);
        }
        if($result){
            alert(1,'操作成功');
        }else{
            alert(0,'操作失败');
        }
    }
    public function addD($company,$username,$pwd,$pwd2,$name,$email){
        if($company==''){
            alert(0,'公司名称不能为空');
        }
        if($username==''){
            alert(0,'用户名不能为空');
        }
        if($pwd==''){
            alert(0,'密码不能为空');
        }
        if($pwd2!=$pwd){
            alert(0,'两次密码不相同');
        }
        if($email==''){
            alert(0,'E-mail不能为空');
        }
        // if($sex==''){
            // alert(0,'性别不能为空');
        // }
        if($name==''){
            alert(0,'姓名不能为空');
        }
        if(!email($email)){
            alert(0,'邮箱地址错误');
        }
        if(!mobile($username)){
            alert(0,'手机号码错误');
        }
        if(M("user")->where("username='".$username."'")->count()>=1){
            alert(0,'用户名已经存在！');
        }
        if(M("user")->where("company='".$company."'")->count()>=1){
            alert(0,'公司名称已经存在！');
        }
        if(M("user")->where("email='".$email."'")->count()>=1){
            alert(0,'电子邮箱已经存在！');
        }
        $data['salt']=rand(10000,99999);
        $data['username']=$username;
        $data['company']=$company;
        $data['password']=md5($pwd.$data['salt']);
        $data['name']=$name;
        $data['email']=$email;
        // $data['sex']=$sex;
        $data['operator']=session('admin');
        $result=M("user")->add($data);
        if($result){
            if($this->createDb(C('DB_PREFIX_T').$username)){
                alert(1,'添加成功');
            }else{
                alert(0,'添加失败，请重试');
            }
        }else{
            alert(0,'添加失败，请重试');
        }
    }
    protected function createDb($username){
        $m=M();
        $f=C('DB_PREFIX_T');
        $db_name=array('category','department','list','list_product','product','role','root','massage');
        $m->execute("CREATE DATABASE ".$username);
        foreach($db_name as $v){
            $m->execute("CREATE TABLE ".$username.".".$f.$v." LIKE ".$f."main.".$f.$v);
            if($v=='category' || $v=='root' || $v=='config'){
                $m->execute("INSERT INTO ".$username.".".$f.$v." SELECT * FROM ".$f."main.".$f.$v);
            }
        }
        return true;
    }
    public function add(){
        $this->display();
    }
    public function edit($id){
        if($id=='' || !is_numeric($id)){
            alert(0,'操作有误');
        }
        $list=M('user')->find($id);
        if(!$list){
            alert(0,'操作有误');
        }else{
            $this->assign('list',$list);
            $this->display();
        }
    }
    public function editD($id,$company,$pwd,$pwd2,$name,$email){
        if($company==''){
            alert(0,'公司名称不能为空');
        }
        if($email==''){
            alert(0,'E-mail不能为空');
        }
        if($name==''){
            alert(0,'姓名不能为空');
        }
        if(!email($email)){
            alert(0,'邮箱地址错误');
        }
        if(M("user")->where("company='".$company."' and id<>'".$id."'")->count()>=1){
            alert(0,'公司名称已经存在！');
        }
        if(M("user")->where("email='".$email."' and id<>'".$id."'")->count()>=1){
            alert(0,'电子邮箱已经存在！');
        }
        $data['company']=$company;
        if($pwd!=''){
            if($pwd2!=$pwd){
                alert(0,'两次密码不相同');
            }
            $data['salt']=rand(10000,99999);
            $data['password']=md5($pwd.$data['salt']);
        }
        $data['name']=$name;
        $data['email']=$email;
        $data['sex']=$sex;
        $data['operator']=session('admin');
        $result=M("user")->where(array('id'=>$id))->save($data);
        if($result){
            alert(1,'修改成功');
        }else{
            alert(0,'修改失败，请重试');
        }
    }
    public function del($id){
        if($id==''){
            alert(0,'操作有误');
        }
        $group_id=explode('@',$id);
        $i=0;
        foreach($group_id as $id){
            $username=M("user")->where("id='".$id."'")->getField('username');
            $true=M()->execute("drop database ".C('DB_PREFIX_T').$username);
            if($true){
                $result= M("user")->delete(ltrim($id,','));
                $i+=$result*1;
            }
        }
        if(count($group_id)==$i){
            alert(1,'全部删除成功');
        }elseif($i>0){
            alert(1,'删除'.$i."个/共".count($group_id)."个");
        }else{
            alert(0,'删除失败');
        }
    }
	//升级
	public function updateAll(){
		$m=M('User');
		$list=$m->order('id asc')->select();
		require_once('./cloudAPP/Admin/Common/DBManage.class.php');
		foreach($list as $k=>$v){
			$dbname=C('DB_PREFIX_T').$v['username'];//数据库名称
			echo "<div style='font-size:12px;'><br>当前操作erp：".$v['company']."<br><br><br>";
			//使用读取写入方式导入
			$db = new \DBManage(C('DB_HOST'),C('DB_USER'),C('DB_PWD'),$dbname,'utf8');
			//导入
			$db->restore('./data/ue.sql');
			unset($db);
		}
		
		$dbname=C('DB_PREFIX_T').'main';//数据库名称
		echo "<div style='font-size:12px;'><br>当前操作erp：默认数据库.<br><br><br>";
		//使用读取写入方式导入
		$db = new \DBManage(C('DB_HOST'),C('DB_USER'),C('DB_PWD'),$dbname,'utf8');
		//导入
		$db->restore('./data/ue.sql');
		unset($db);
		@unlink('./data/update.sql');//删除文件
    }
	//清空
	public function truncateAll(){
		$m=M('User');
		$id=I('id');
		$user_info=$m->where(array('id'=>$id))->find();
		require_once('./cloudAPP/Admin/Common/DBManage.class.php');
		$dbname=C('DB_PREFIX_T').$user_info['username'];//数据库名称
		echo "<div style='font-size:12px;'><br>当前操作erp：".$user_info['company']."<br><br><br>";
		//使用读取写入方式导入
		$db = new \DBManage(C('DB_HOST'),C('DB_USER'),C('DB_PWD'),$dbname,'utf8');
		//导入
		$db->restore('./data/truncate_erp.sql');
		unset($db);
    }
	
	//角色列表
    public function department(){
        $f=C('DB_PREFIX');
        $list = M('DepartmentCompany')->order('created_at desc')->select();
        $this->assign('list',$list);
        $this->display();
    }
	public function department_add(){
		$root=M('RootCompany')->order("sort")->select();
        $new_arr=array();
		foreach($root as $k=>$v){
            if($v['pid']==0){//顶级菜单
                foreach($root as $j=>$u){
					if($v['id']==$u['pid']){
						foreach($root as $js=>$us){
							if($u['id']==$us['pid']){
								foreach($root as $jss=>$uss){
									if($us['id']==$uss['pid']){
											$us['child'][]=$uss;
									}
								}
								$u['child'][]=$us;
							}
						}
						$v['child'][]=$u;
					}
				}
				$new_arr[]=$v;
            }
        }
		// dump($new_arr);
		// die;
		$this->assign('list',$new_arr);
        $this->display();
    }
	public function department_addD($name,$group_id){
        $this->p = M('RootCompany');
        if($name==''){
            alert(0,'部门名称为空');
        }
        if($group_id==''){
            alert(0,'权限不能为空');
        }
        $count=$this->p->where("name='".$name."'")->count();
        if($count>0){
            alert(0,'名称已经存在');
        }
        //////权限检查，是否具备这些权限
        $arr_id=explode(',',$group_id);
        foreach($arr_id as $v){
            if(!is_numeric($v)){
                alert('操作有误');
            }
        }
        $where['id']=array('IN',$arr_id);
        $result=$this->p->where($where)->getField('name',true);
        if(count($result)!=count($arr_id)){
            alert('操作有误');
        }
        $data['name']=$name;
        $massage=session('admin');
        $data['operator']=$massage;
        $this->product = M('DepartmentCompany');
        $data['root_group_id']=$group_id;
        $result=$this->product->add($data);
		// echo $this->product->getlastsql();
        if($result){
            alert(1,'添加成功');
        }else{
            alert(0,'添加失败');
        }
    }
    public function department_edit($id){
        if($id==''){
            echo "错误";
        }
		
		$root=M('RootCompany')->order("sort")->select();
		$this->product = M('DepartmentCompany');
		$this->data=$this->product->find($id);
        $root_id=$this->product->where(array('id'=>$id))->getField('root_group_id');
        $arr_root=explode(',',$root_id);
        $new_arr=array();
		foreach($root as $k=>$v){
			if(in_array($v['id'],$arr_root)){
				$v['checked']=1;
			}
            if($v['pid']==0){//顶级菜单
                foreach($root as $j=>$u){
					if(in_array($u['id'],$arr_root)){
						$u['checked']=1;
					}
					if($v['id']==$u['pid']){
						foreach($root as $js=>$us){
							if(in_array($us['id'],$arr_root)){
								$us['checked']=1;
							}
							if($u['id']==$us['pid']){
								foreach($root as $jss=>$uss){
									if(in_array($uss['id'],$arr_root)){
										$uss['checked']=1;
									}
									if($us['id']==$uss['pid']){
											$us['child'][]=$uss;
									}
								}
								$u['child'][]=$us;
							}
						}
						$v['child'][]=$u;
					}
				}
				$new_arr[]=$v;
            }
        }
        $this->assign('list',$new_arr);
        $this->display();
    }
    public function department_editD($id,$group_id){
        $this->p = M('RootCompany');
        if($group_id==''){
            alert(0,'权限不能为空');
        }
        //////权限检查，是否具备这些权限
        $arr_id=explode(',',$group_id);
		// dump($arr_id);
		// die;
        foreach($arr_id as $v){
            if(!is_numeric($v)){
                alert('操作有误');
            }
        }
        $where['id']=array('IN',$arr_id);
        $result=$this->p->where($where)->getField('name',true);
        if(count($result)!=count($arr_id)){
            alert('操作有误');
        }
        $massage=session('admin');
        $data['operator']=$massage;
        $this->product = M('DepartmentCompany');
        $data['root_group_id']=$group_id;
        $result=$this->product->where(array('id'=>$id))->save($data);
        if($result){
            alert(1,'修改成功');
        }else{
            alert(0,'修改失败');
        }
    }
    public function department_del($id){
        if($id==''){
            alert(0,'操作有误');
        }
        ///////$id=1@2@3
        $group_id=explode('@',$id);
        $id=implode(',',$group_id);
        $result=M('DepartmentCompany')->delete($id);
        if($result){
            alert(1,'成功删除了'.$result.'条数据，共'.count($group_id).'条');
        }else{
            alert(0,'删除失败');
        }
    }

	
}